<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">🌸 智慧花卉实时监测中心</text>
      <text v-if="!connected" class="status connecting">🔌 正在连接中...</text>
      <text v-else class="status ok">✅ 已连接服务器</text>
    </view>

    <!-- 实时数据卡片 -->
    <view class="card-box">
      <view class="card">
        <text class="card-title">🌡 温度</text>
        <text class="card-value">{{ realtime.temp.toFixed(2) }} ℃</text>
      </view>

      <view class="card">
        <text class="card-title">💧 空气湿度</text>
        <text class="card-value">{{ realtime.humi.toFixed(2) }} %</text>
      </view>

      <view class="card">
        <text class="card-title">🌱 土壤湿度</text>
        <text class="card-value">{{ realtime.soilM }}</text>
      </view>

      <view class="card">
        <text class="card-title">☔ 降雨量</text>
        <text class="card-value">{{ realtime.raindrops }}</text>
      </view>
    </view>

    <!-- 花卉种类选择 -->
    <view class="type-section">
      <text class="section-title">🌼 花卉品种</text>
      <scroll-view scroll-x class="type-scroll">
        <view
          v-for="(item, index) in varietyList"
          :key="index"
          class="type-item"
          :class="{ active: item === selectedVariety }"
          @click="selectVariety(item)"
        >
          {{ item }}
        </view>
      </scroll-view>
    </view>

    <!-- 历史警报 -->
    <view class="alert-section">
      <text class="section-title">⚠️ 历史警报信息</text>

      <view v-if="alertList.length === 0 && !loading" class="empty">
        暂无警报记录
      </view>

      <scroll-view
        scroll-y
        class="alert-list"
        @scrolltolower="loadMore"
        :lower-threshold="100"
      >
        <view
          v-for="(alert, index) in alertList"
          :key="index"
          :class="['alert-item', getAlertLevel(alert.message)]"
        >
          <view class="alert-header">
            <text class="alert-time">{{ alert.time }}</text>
            <text class="alert-level">{{ getAlertLabel(alert.message) }}</text>
          </view>
          <text class="alert-message">{{ alert.message }}</text>
        </view>

        <view v-if="loading" class="loading">加载中...</view>
        <view v-if="finished && alertList.length > 0" class="no-more">没有更多数据</view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import { connectWebSocket, closeWebSocket, getWebSocket } from '@/utils/websocket.js'

// ============ 实时数据 ============
const connected = ref(false)
const realtime = ref({ temp: 0, humi: 0, soilM: 0, raindrops: 0 })
let ws = null

const initWebSocket = () => {
  // 如果已存在 socket，先关闭（保持与示例一致）
  if (getWebSocket()) closeWebSocket()

  ws = connectWebSocket('ws://localhost:8080/ws/flower', (msg) => {
    try {
      const json = JSON.parse(msg)
      // 服务器推送格式示例：{"temp":28.0,"humi":44.0,"soilM":9015,"raindrops":16000}
      realtime.value = {
        temp: Number(json.temp ?? realtime.value.temp),
        humi: Number(json.humi ?? realtime.value.humi),
        soilM: json.soilM ?? realtime.value.soilM,
        raindrops: json.raindrops ?? realtime.value.raindrops
      }
    } catch (e) {

    }
  })

  ws.onOpen(() => {
    connected.value = true
  })

  ws.onClose(() => {
    connected.value = false
  })

  ws.onError(() => {
    connected.value = false
  })
}

onShow(() => initWebSocket())
onHide(() => closeWebSocket())

// ============ 花卉种类与历史警报 ============
const varietyList = ref([])
const selectedVariety = ref('')
const alertList = ref([])
const page = ref(1)
const size = ref(10) // 默认每页 10 条，可不传服务端默认也会生效
const loading = ref(false)
const finished = ref(false)

const token = `Bearer ${uni.getStorageSync('token') || ''}`

// 获取花卉种类
const getVarietyList = async () => {
  try {
    const res = await uni.request({
      url: 'http://localhost:8080/device/show/showVariety',
      method: 'POST',
      header: { Authorization: token }
    })
    if (res.statusCode === 200) {
      // 假设返回的是字符串数组：["rose","tulip",...]
      varietyList.value = res.data || []
      if (varietyList.value.length > 0) {
        selectVariety(varietyList.value[0])
      }
    } else {
      console.error('获取花卉种类失败，状态码:', res.statusCode)
    }
  } catch (e) {
    console.error('获取花卉种类异常:', e)
  }
}

// 解析报警字符串：与池塘示例一致，形如 "2025-11-01 15:30:00 温度超出阈值；空气湿度超出阈值；"
const parseAlert = (str) => {
  if (!str || typeof str !== 'string') {
    return { time: '', message: '' }
  }
  const parts = str.trim().split(' ')
  if (parts.length >= 3) {
    const time = `${parts[0]} ${parts[1]}`
    const message = parts.slice(2).join(' ').replace(/；$/, '')
    return { time, message }
  }
  return { time: '', message: str.trim().replace(/；$/, '') }
}

// 拉取历史警报，reset=true 表示重置（切换品种或下拉刷新）
const loadAlerts = async (reset = false) => {
  if (loading.value ) return
  loading.value = true
  if (reset) {
	finished.value = false
    page.value = 1
    alertList.value = []
  }

  // 防御性检查：没有选中品种不请求
  if (!selectedVariety.value) {
    console.warn('selectedVariety 为空，跳过请求')
    loading.value = false
    return
  }
  
  try {
	const url = `http://localhost:8080/device/show/flowerAlertHistory?variety=${encodeURIComponent(selectedVariety.value)}&page=${page.value}&size=${size.value}` 
	console.log("请求地址：", url)
	
    const res = await uni.request({
      url,
      method: 'POST',
      header: { Authorization: token }
    })
	
    if (res.statusCode === 200) {
      let list = res.data
      // 后端可能返回字符串形式的 JSON，也可能直接返回数组，兼容处理
      if (typeof list === 'string') {
        try {
          list = JSON.parse(list)
        } catch {
          // 如果不是 JSON，后端也可能直接返回单条提示字符串，例如 "未找到任何历史数据"
          if (list === '未找到任何历史数据' || list === '暂无数据') {
            list = []
          } else {
            // 把单条字符串放入数组以便解析
            list = [list]
          }
        }
      }
	  
      // 解析每条记录
      const parsed = (Array.isArray(list) ? list : []).map(parseAlert)

      if (parsed.length === 0) {
        // 如果第一页就没有数据，标记 finished
        if (page.value === 1) alertList.value = []
        finished.value = true
      } else {
        alertList.value.push(...parsed)
        // 如果本次返回的数据小于 page size，说明已无更多
        if (parsed.length < size.value) finished.value = true
        page.value++
      }
    } else {
      console.error('获取历史警报失败，状态码:', res.statusCode)
    }
  } catch (e) {
    console.error('获取历史警报异常:', e)
  } finally {
    loading.value = false
  }
}

// 切换品种
const selectVariety = (v) => {
  selectedVariety.value = v
  loadAlerts(true)
}

// 下滑触底加载更多
const loadMore = () => {
  if (!finished.value) loadAlerts()
}

// 报警等级，简单关键字判断（可按需调整）
const getAlertLevel = (message) => {
  if (!message) return 'normal'
  if (message.includes('严重') || message.includes('超出') || message.includes('过高') || message.includes('低于')) return 'danger'
  if (message.includes('偏高') || message.includes('偏低')) return 'warning'
  return 'normal'
}

const getAlertLabel = (message) => {
  if (!message) return ''
  if (message.includes('严重')) return '严重'
  if (message.includes('超出') || message.includes('低于') || message.includes('过低')) return '警告'
  return '提示'
}

onMounted(() => {
  getVarietyList()
})
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f7f7f7;
  min-height: 100vh;
  padding: 40rpx;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
}

.title {
  font-size: 38rpx;
  font-weight: bold;
  color: #333;
}

.status {
  display: block;
  margin-top: 10rpx;
  font-size: 26rpx;
}

.status.connecting {
  color: #ff9800;
}

.status.ok {
  color: #22bb33;
}

.card-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  margin-bottom: 60rpx;
}

.card {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.card-title {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.card-value {
  font-size: 48rpx;
  font-weight: bold;
  color: #2c7ef8;
}

/* 品种选择 */
.type-section {
  width: 100%;
  margin: 20rpx 0;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  color: #333;
}

.type-scroll {
  display: flex;
  flex-direction: row;
  gap: 20rpx;
}

.type-item {
  background: #fff;
  padding: 18rpx 28rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  color: #555;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.05);
}

.type-item.active {
  background: #e94f8a;
  color: #fff;
}

/* 历史警报 */
.alert-section {
  width: 100%;
}

.alert-list {
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
  max-height: 600rpx;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 40rpx;
}

.alert-item {
  border-radius: 16rpx;
  padding: 18rpx 20rpx;
  margin-bottom: 16rpx;
  color: #fff;
}

.alert-item.normal {
  background-color: #4caf50;
}

.alert-item.warning {
  background-color: #ff9800;
}

.alert-item.danger {
  background-color: #e74c3c;
}

.alert-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8rpx;
}

.alert-time {
  font-size: 24rpx;
}

.alert-level {
  font-size: 24rpx;
  font-weight: bold;
}

.alert-message {
  font-size: 28rpx;
}

.empty {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 40rpx 0;
}

.loading, .no-more {
  text-align: center;
  color: #888;
  padding: 24rpx 0;
}
</style>
